package com.sayyi.demo.mybatis;

import com.sayyi.demo.mybatis.domain.Blog;
import com.sayyi.demo.mybatis.mapper.BlogMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author xuchuang
 * date 2021/12/16 2:08 PM
 */
@Slf4j
public class Main {

    public static void main(String[] args) throws IOException {
        final InputStream stream = Resources.getResourceAsStream("mybatis-config.xml");
        final SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(stream);

        // 使用 wireshark 进行观测，可以发现，虽然多次开启了session，但是连接实际上只建立了一次
        // 每次开启sqlsession的时候，都会修改连接的 autocommit 属性
        // sqlsession内置 Executor，这个东西会受到 BATCH 参数的影响
        // Executor，在启用缓存的情况下，会在外部包裹 CachingExecutor

        // sqlsession 关闭时，会将连接状态调整为 autocommit = 1，然后调用连接的 close方法
        // 实际的 connection 被 PooledConnection 动态代理了，当调用 close 方法时，不会关闭连接，而是将连接返回连接池
        try (final SqlSession sqlSession = sqlSessionFactory.openSession()) {
            BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
            Blog blog = mapper.selectBlog(1);
            log.info("insert result: {}", blog);
        }

        try (SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false)) {
            BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
            Blog blog = new Blog();
            blog.setTitle("title");
            blog.setContent("content");
            mapper.save(blog);
            sqlSession.commit();
            log.info("with transaction: {}" ,blog);
        }

        // 这里可以看到，默认是关闭自动提交的
        try (final SqlSession sqlSession = sqlSessionFactory.openSession()) {
            BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
            Blog blog = new Blog();
            blog.setTitle("title-1");
            blog.setContent("content-1");
            mapper.save(blog);
            log.info("without transaction: {}", blog);
        }
    }
}
